using ControlCenter.ApplicationService;
using ControlCenter.Model;
using ControlCenter.Model.BizEntities;
using ControlCenter.Operation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MingYuanyun.WebApi.Abstractions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using ControlCenter.Model.WebApiDto;
using ControlCenterService.WebApi.Internal;

namespace ControlCenterService.WebApi.Controllers
{
    /// <summary>
    /// 包管理Api
    /// </summary>
    [Route("[controller]")]
    public class PackageManagementController : BasicController
    {
        private readonly IPackageManagementService _packageManagementService;

        /// <summary>
        /// 类初始化
        /// </summary>
        /// <param name="packageManagementService"></param>
        public PackageManagementController(IPackageManagementService packageManagementService)
        {
            _packageManagementService = packageManagementService;
        }

        #region -- Studio Api -------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 发布程序包到控制中心（使用者：Studio）
        /// </summary>
        /// <param name="packageInfoDto"></param>
        /// <param name="package"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Publish")]
        [ClientApiFilter]
        public async Task<HttpRequestResult<bool>> Publish(PackageInfoDto packageInfoDto, IFormFile package)
        {
            return OkHttpRequestResult(await _packageManagementService.SavePackages(packageInfoDto, package));
        }
        #endregion

        /// <summary>
        /// 下载包（使用者：ROBOT）
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{packageId}/DownloadPackage")]
        [ClientApiFilter]
        public async Task<ActionResult> DownloadPackage(Guid packageId)
        {
            var package = await _packageManagementService.ReadPackageFile(packageId);
            var reportDoc = new FileContentResult(package.fileStream, "application/nupkg") { FileDownloadName = $"{package.packageInfoDto.ProjectName}.{package.packageInfoDto.Version}.nupkg" };
            return reportDoc;
        }

        #region -- 机器人的包管理 -------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 获取所有机器人的应用摘要信息列表（使用者：控制中心）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("QueryRobotPackageShortInfo")]
        public async Task<HttpRequestResult<IEnumerable<RobotPackageShortInfo>>> QueryRobotPackageShortInfo()
        {
            return OkHttpRequestResult(await _packageManagementService.QueryRobotPackageShortInfo());
        }

        /// <summary>
        /// 查询机器人的所有任务包（使用者：ROBOT）
        /// </summary>
        /// <param name="robotId">机器人id  ：AF936873-1E12-42F8-AC34-5821886EF2BF</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{robotId}/QueryPackage")]
        [ClientApiFilter]
        public async Task<HttpRequestResult<IEnumerable<RobotPackageInfo>>> QueryPackage(Guid robotId)
        {
            return OkHttpRequestResult(await _packageManagementService.QueryRobotPackageInfo(robotId));
        }

        /// <summary>
        /// 查询机器人待执行的任务包（使用者：ROBOT）
        /// </summary>
        /// <param name="robotId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{robotId}/QueryWaitExectionPackage")]
        [ClientApiFilter]
        public async Task<HttpRequestResult<IEnumerable<WaitExecutionPackageDto>>> QueryWaitExectionPackage(Guid robotId)
        {
            return OkHttpRequestResult(await _packageManagementService.QueryRobotWaitExectionPackage(robotId));
        }

        /// <summary>
        /// 读取机器人的包信息列表，供编辑机器人包使用（使用者：控制中心）
        /// </summary>
        /// <param name="robotId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("QuerySaveRobotPackageInfo")]
        public async Task<HttpRequestResult<IEnumerable<SaveRobotPackageInfo>>> QuerySaveRobotPackageInfo(Guid robotId)
        {
            return OkHttpRequestResult(await _packageManagementService.QuerySaveRobotPackageInfo(robotId));
        }

        /// <summary>
        /// 保存机器人的包及设定数据（使用者：控制中心）
        /// </summary>
        /// <param name="saveDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveRobotPackageExecCycleInfo")]
        public async Task<HttpRequestResult> SaveRobotPackageExecCycleInfo([FromBody] SaveRobotInfoDto saveDto)
        {
            var ret = await _packageManagementService.UpdateRobotPackageInfo(saveDto);
            if (ret)
            {
                return OkHttpRequestResult();
            }
            else
            {
                return ErrorHttpRequestResult("数据保存失败！");
            }
        }

        /// <summary>
        /// 更新机器人的包状态（启用/停用）（使用者：控制中心）
        /// </summary>
        /// <param name="rpId"></param>
        /// <param name="packageStatus"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("UpdateRobotPackagePackageStatus")]
        public async Task<HttpRequestResult> UpdateRobotPackagePackageStatus(Guid rpId, int packageStatus)
        {
            await _packageManagementService.UpdateRobotPackagePackageStatus(rpId, packageStatus);
            return OkHttpRequestResult(null);
        }

        /// <summary>
        /// 删除机器人的包（使用者：控制中心）
        /// </summary>
        /// <param name="rpId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("DeleteRobotPackage")]
        public async Task<HttpRequestResult> DeleteRobotPackage(Guid rpId)
        {
            await _packageManagementService.DeleteRobotPackage(rpId);
            return OkHttpRequestResult(null);
        }
        #endregion


        #region -- 包管理 -------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 查询包（使用者：控制中心）
        /// </summary>
        /// <param name="paramDto"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("QueryPackageInfo")]
        public async Task<HttpRequestResult<PagedData<ProjectPackageInfo>>> QueryPackageInfo(PackageQueryDto paramDto)
        {
            return OkHttpRequestResult(await _packageManagementService.QueryPackageInfo(paramDto));
        }

        /// <summary>
        /// 获取包信息（使用者：控制中心）
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("FindPackageInfo")]
        public async Task<HttpRequestResult<ProjectPackageInfo>> FindPackageInfo(Guid packageId)
        {
            return OkHttpRequestResult(await _packageManagementService.FindPackageInfo(packageId));
        }

        /// <summary>
        /// 更新包信息，不存在时新增（使用者：控制中心）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SavePackageInfo")]
        public async Task<HttpRequestResult<bool>> SavePackageInfo([FromBody]ProjectPackageInfo param)
        {
            var saveRet = await _packageManagementService.SavePackageInfo(param);
            if (saveRet.Item1)
            {
                return OkHttpRequestResult<bool>();
            }
            else
            {
                return ErrorHttpRequestResult<bool>(saveRet.Item2);
            }
        }

        /// <summary>
        /// 删除包，已被机器人使用的包不允许删除（使用者：控制中心）
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("DeletePackageInfo")]
        public async Task<HttpRequestResult> DeletePackageInfo(Guid packageId)
        {
            var ret = await _packageManagementService.DeletePackageInfo(packageId);
            if (ret.Item1)
            {
                return OkHttpRequestResult();
            }
            else
            {
                return ErrorHttpRequestResult(ret.Item2);
            }
        }
        #endregion

        ///// <summary>
        ///// 更新机器人，包关系，是否已安装，是否需要安装（使用者：控制中心）
        ///// { "RobotId": "AF936873-1E12-42F8-AC34-5821886EF2BF", "packageId": "7342B976-89E1-4D6F-884F-5B854203BF6B", "packageStatus": 1, "IsInstall": false}
        ///// </summary>
        ///// <param name="updatePackageStatusDto"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[Route("UpdatePackageStatus")]
        //public async Task<HttpRequestResult<bool>> UpdatePackageStatus([FromBody]UpdatePackageStatusDto updatePackageStatusDto)
        //{
        //    return OkHttpRequestResult(await _packageManagementService.UpdatePackageStatus(updatePackageStatusDto));
        //}

        #region -- 包管理 -------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 查询指定应用包的参数配置
        /// </summary>
        /// <param name="packageId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("QueryPackageConfig")]
        public async Task<HttpRequestResult<List<PackageConfigItem>>> QueryPackageConfig(Guid packageId)
        {
            return OkHttpRequestResult(await _packageManagementService.QueryPackageConfig(packageId));
        }

        /// <summary>
        /// 更新应用包的参数配置
        /// </summary>
        /// <param name="packageConfigItems"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdatePackageConfig")]
        public async Task<HttpRequestResult> UpdatePackageConfig([FromBody]List<PackageConfigItem> packageConfigItems)
        {
            var ret = await _packageManagementService.UpdatePackageConfig(packageConfigItems);
            if (ret.Item1)
            {
                return OkHttpRequestResult();
            }
            else
            {
                return ErrorHttpRequestResult(ret.Item2);
            }
        }
        #endregion
    }
}
